package com.alter.service;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.alibaba.fastjson.JSONObject;
import com.alter.auth.manager.TokenManager;
import com.alter.auth.model.TokenModel;
import com.alter.domain.UserInfo;
import com.alter.mapper.UserInfoMapper;

@Service
public class UserInfoService {
	
	@Autowired
	private UserInfoMapper mapper;
	
	@Autowired
    private TokenManager tokenManager;
	
	public UserInfo getUserInfo(String loginId){
		return mapper.getUserInfo(loginId);
	}
	
	public UserInfo getUserInfoById(String userId){
		return mapper.getUserInfoById(userId);
	}
	
	public void registerUser(UserInfo user){
		Date now = new Date();
        SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = outFormat.format(now);
		user.setCreateDate(date);
		user.setUserStatus("1");
		user.setModifyDate(date);
		user.setPsw(DigestUtils.md5DigestAsHex(user.getPsw().getBytes()));
		mapper.insertUserInfo(user);
	}
	
	public JSONObject userLogin(String loginId, String psw){
		JSONObject data = new JSONObject();
		UserInfo userInfo = mapper.getUserInfo(loginId);
		if(userInfo == null){
			data.put("ret", -1005);
	    	data.put("msg", "手机号不存在");
	    	data.put("data", "");
			return data;
		}
		if( !DigestUtils.md5DigestAsHex(psw.getBytes()).equals(userInfo.getPsw()) ){
			data.put("ret", -1006);
	    	data.put("msg", "密码错误");
	    	data.put("data", "");
			return data;
		}
		//生成一个token，保存用户登录状态
        TokenModel model = tokenManager.createToken(userInfo.getId());
        data.put("ret", 1);
    	data.put("msg", "登录成功");
    	data.put("data", model);
		return data;
	}
	
	
	
}
